<?php
/**
 * Created by PhpStorm.
 * User: mr.lee
 * Date: 2018/10/19
 * Time: 10:48 AM
 */

namespace app\index\controller;


use Alipay\Alipayobj;
use app\common\controller\ActionLogs;
use app\common\controller\CreateNotify;
use app\common\controller\Deviceobj;
use app\common\model\Agent;
use app\common\model\Merchant;
use app\common\model\Paylog;
use app\common\model\WxOpen;
use Bank\HuifuServer;
use think\Controller;
use think\Request;
use think\Session;
use Wechat\Wxobjopen;

class Huifupay extends Controller
{
    public function test()
    {
        $request = Request()->param();
        $request['id'] = 819;
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $request['id'];
        $config = $Merchant->where($map)->find();
        $total_fee = "0.01";
        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $JsonData['appId'] = $users['authorizer_appid'];
        $JsonData['termOrdId'] = $this->getorder($request['id']);
        $JsonData['memberId'] = $config['huifu_memberid'];
        $JsonData['merOperId'] = $config['huifu_meroperid'];
        $JsonData['ordAmt'] = number_format($total_fee, 2, ".", "");
        $JsonData['authCode'] = "134633151858779622";
        $JsonData['apiVersion'] = "2.0.0.1";
        $JsonData['goodsDesc'] = "快捷支付";

        foreach ($JsonData as $k => $v) {
            $JsonData2[$k] = urlencode($v);
        }
        $JsonData2['merPriv'] = array("merNoticeUrl" => "https://" . $_SERVER ['SERVER_NAME'] . "/huifunotify.php/paynotice");
        $JsonData3 = json_encode($JsonData2, JSON_UNESCAPED_UNICODE);
        $HuifuServer = new HuifuServer();
        $data['checkValue'] = $HuifuServer->sign($JsonData3);
        $data['jsonData'] = $JsonData3;
        $data['traceNo'] = "H501-" . date('YmdHis') . rand(100, 999);
        $res = $HuifuServer->b2c_pay($data);
//        $this->create_paylog($request, 2);
        if ($res['respCode'] == "000000") {
            $jsonData = json_decode($res['jsonData'], true);
            $payinfo = json_decode($jsonData['payInfo'], true);
            $re_param['result_code'] = "SUCCESS";
            $re_param['result_msg'] = $res['respDesc'];
            $re_param['info'] = $payinfo;
        } else {
            $re_param['result_code'] = "FAIL";
            $re_param['result_msg'] = $res['respDesc'];
        }
        var_dump($re_param);
    }

    public function wxpay()
    {
        $request = request();
        Session::set('openid', null);
        $map['id'] = $request->param('id');
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $user = $Merchant->where($map)->find();
        $config = $Agent->where(array('id' => $user['agent']))->find();
        $users = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
            // 'partnerkey'=>$agent['partnerkey']
        );

        $weObj = new Wxobjopen($options);
        $openid = Session::get('openid');
        if (strlen($openid) <= 10) {
            $info = $weObj->getOpenoauthAccessToken();
            if (!$info) {
                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("huifupay/wxpay", array('id' => $request->param('id')));
                $url = $weObj->getopenOauthRedirect($callback, '', 'snsapi_base');

                header("Location: $url");
                exit();
            } else {
                $openid = $info['openid'];
                session('openid', $openid);
                $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
                $jssdk = $weObj->getJsSign($url);
            }
        }
        $this->assign('jssdk', $jssdk);

        $this->assign("channel", "wxpay");
        $this->assign("headimg", $user['img']);
        $this->assign('mach', $user);
        $this->assign('id', $request->param('id'));
        $this->assign('openid', $openid);
        return $this->fetch();


    }

    public function wxpay_send()
    {
        $request = Request()->param();

        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $map['id'] = $request['id'];
        $config = $Merchant->where($map)->find();

        $agent = $Agent->where(array('id' => $config['agent']))->find();
        $users = $WxOpen->where(array('id' => $agent['wx_open_id']))->find();
        $JsonData['ordAmt'] = number_format(request()->post('price'), 2, ".", "");
        $JsonData['apiVersion'] = "2.0.0.1";
        $JsonData['payChannelType'] = "W1";
        $JsonData['appId'] = $users['authorizer_appid'];
        $JsonData['isRaw'] = "1";
        $JsonData['openId'] = request()->post('sub_openid');
//        $JsonData['buyerLogonId']= "";
//        $JsonData['buyerId']= "";
        $JsonData['termOrdId'] = request()->post('orderid');
//        $JsonData['outOrdId'] = request()->post('orderid');;
        $JsonData['goodsDesc'] = "快捷支付";
        $JsonData['memberId'] = $config['huifu_memberid'];
        $JsonData['merOperId'] = $config['huifu_meroperid'];
        foreach ($JsonData as $k => $v) {
            $JsonData2[$k] = urlencode($v);
        }
        $JsonData2['merPriv'] = array("merNoticeUrl" => "https://" . $_SERVER ['SERVER_NAME'] . "/huifunotify.php/paynotice");
        $JsonData3 = json_encode($JsonData2, JSON_UNESCAPED_UNICODE);
        $HuifuServer = new HuifuServer();
        $data['checkValue'] = $HuifuServer->sign($JsonData3);
        $data['jsonData'] = $JsonData3;
        $data['traceNo'] = "H501-" . date('YmdHis') . rand(100, 999);
        $res = $HuifuServer->c2b_pay($data);
        $this->create_paylog($request, 0);
        if ($res['respCode'] == "000000") {
            $jsonData = json_decode($res['jsonData'], true);
            $payinfo = json_decode($jsonData['payInfo'], true);
            $re_param['result_code'] = "SUCCESS";
            $re_param['result_msg'] = $res['respDesc'];
            $re_param['info'] = $payinfo;
        } else {
            $re_param['result_code'] = "FAIL";
            $re_param['result_msg'] = $res['respDesc'];
        }
        return json($re_param);
    }

    public function alipay()
    {
        $request = request();
        $Merchant = new Merchant();
        $users = $Merchant->where(array('id' => $request->param('id')))->find();
        $Agent = new Agent();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $options = array(
            //'token' => $config ["token"], // 填写你设定的key
            //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],
        );
        $aliObj = new Alipayobj($options);
        if ($request->get('auth_code')) {
            $param['app_id'] = $agent['ali_app_id'];
            $param['method'] = "alipay.system.oauth.token";
            $param['charset'] = "UTF-8";
            $param['sign_type'] = "RSA2";
            $param['version'] = '1.0';
            $param['timestamp'] = date('Y-m-d H:i:s');
            $param['grant_type'] = 'authorization_code';
            $param['code'] = $request->get('auth_code');
            $signContent = $aliObj->rsaSign($param, $signType = "RSA2");

            $param['sign'] = $signContent;
            $uid = $aliObj->getuid($param);
            $user = json_decode($uid, true);
            $uid = $user['alipay_system_oauth_token_response']['user_id'];
//            echo $uid;
            $this->assign("headimg", $users['img']);
            $this->assign('shmc', $users['merchant']);
            $this->assign('id', $request->param('id'));
            $this->assign('uid', $uid);
            $this->assign('mach', $users);
            $this->assign("channel", "alipay");

            return $this->fetch();

        } else {
            $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("Huifupay/alipay", array('id' => $request->param('id')));
            $url = $aliObj->getOauthRedirect($callback, '', 'auth_base');
//        echo $url;
//        exit();
            header("Location: $url");
        }

    }

    public function alipay_send()
    {
        try {
            $request = Request()->param();


            $Merchant = new Merchant();
            $Agent = new Agent();
            $map['id'] = $request['id'];
            $config = $Merchant->where($map)->find();

            $agent = $Agent->where(array('id' => $config['agent']))->find();
            $JsonData['ordAmt'] = number_format(request()->post('price'), 2, ".", "");
            $JsonData['apiVersion'] = "2.0.0.1";
            $JsonData['payChannelType'] = "A1";
            $JsonData['appId'] = $agent['ali_app_id'];
            $JsonData['isRaw'] = "1";
//        $JsonData['buyerLogonId']= "";
            $JsonData['buyerId'] = request()->post('buyer_id');
            $JsonData['termOrdId'] = request()->post('orderid');
//        $JsonData['outOrdId'] = request()->post('orderid');;
            $JsonData['goodsDesc'] = "快捷支付";
            $JsonData['memberId'] = $config['huifu_memberid'];
            $JsonData['merOperId'] = $config['huifu_meroperid'];
            foreach ($JsonData as $k => $v) {
                $JsonData2[$k] = urlencode($v);
            }
            $JsonData2['merPriv'] = array("merNoticeUrl" => "https://" . $_SERVER ['SERVER_NAME'] . "/huifunotify.php/paynotice");
            $JsonData3 = json_encode($JsonData2, JSON_UNESCAPED_UNICODE);
            $HuifuServer = new HuifuServer();
            $data['checkValue'] = $HuifuServer->sign($JsonData3);
            $data['jsonData'] = $JsonData3;
            $data['traceNo'] = "H501-" . date('YmdHis') . rand(100, 999);
            $res = $HuifuServer->c2b_pay($data);
            $this->create_paylog($request, 1);
            if ($res['respCode'] == "000000") {
                $jsonData = json_decode($res['jsonData'], true);
                $payinfo = json_decode($jsonData['payInfo'], true);
                $re_param['result_code'] = "SUCCESS";
                $re_param['result_msg'] = $res['respDesc'];
                $re_param['info'] = $payinfo;
            } else {
                $re_param['result_code'] = "FAIL";
                $re_param['result_msg'] = $res['respDesc'];
            }
        } catch (\Exception $e) {
            $re_param['code'] = $e->getMessage();
        }
        return json($re_param);
    }

    public function payover()
    {
        $orderid = request()->param('orderid');
        $sj = $this->order_query($orderid);

        if ($sj['result_code'] == "SUCCESS") {

            $data = 0;
        } else {
            $data = 1;
        }
        echo $data;
    }

    public function order_query($orderid)
    {
        $Paylog = new Paylog();
        $orderinfo = $Paylog->where('orderid', $orderid)->find();
        $Merchant = new Merchant();
        $mchinfo = $Merchant->where('id', $orderinfo['mid'])->field('huifu_memberid,huifu_meroperid')->find();
        $JsonData['memberId'] = $mchinfo['huifu_memberid'];
        $JsonData['merOperId'] = $mchinfo['huifu_meroperid'];
        $JsonData['termOrdId'] = $orderinfo['orderid'];
        $JsonData['ordType'] = "1";
        $JsonData['apiVersion'] = "2.0.0.1";
        $JsonData['transDate'] = date('Ymd', $orderinfo['add_time']);
        $JsonData3 = json_encode($JsonData, JSON_UNESCAPED_UNICODE);

        $HuifuServer = new HuifuServer();
        $data['checkValue'] = $HuifuServer->sign($JsonData3);
        $data['jsonData'] = $JsonData3;
        $res = $HuifuServer->order_query($data);
        if ($res['respCode'] == "000000") {

            $postStr = json_decode($res['jsonData'], true);
            if ($postStr['transStat'] == "S") {

                $map['orderid'] = $postStr['termOrdId'];
                $save_datas['orderno'] = $postStr['outTransId'];
                $save_datas['trade_no'] = $postStr['partyOrderId'];
                $save_datas['pay_statu'] = 1;
                $save_datas['pay_time'] = date('Y-m-d H:i:s', strtotime($postStr['transDate'] . $postStr['transTime']));

                $Paylog->save($save_datas, $map);
                if ($orderinfo['tzzt'] == '0') {
                    $s = action('Wxauth/sendtemplate', array($orderinfo['mid'], $orderinfo['orderid']));
                    $Deviceobj = new Deviceobj();
                    $s=$Deviceobj->ylb_sendvoice($postStr['termOrdId']);
                    action('Index/sendprint', array($orderinfo));
                    $da['tzzt'] = 1;
                    $da['tzmsg'] = json_encode($s, JSON_UNESCAPED_UNICODE);
                    $Paylog->save($da, ['orderid' => $orderinfo['orderid']]);
                    $notify_param['merchantid']=$orderinfo['mid'];
                    $notify_param['out_trade_no']=$orderinfo['orderid'];
                    $CreateNotify=new CreateNotify();
                    $CreateNotify->pay_notify($notify_param);
                }
                $datas['result_code'] = "SUCCESS";
                $datas['result_msg'] = "支付成功";
            }elseif ($postStr['transStat'] == "F") {
                $datas['result_code'] = "FAIL";
                $datas['result_msg'] = "支付失败";
            }elseif ($postStr['transStat'] == "P") {
                $datas['result_code'] = "FAIL";
                $datas['result_msg'] = "支付处理中";
            }
        } else {
            $datas['result_code'] = "FAIL";
            $datas['result_msg'] = $res['respDesc'];
        }

      return $datas;
    }

    public function wxorderinfo()
    {

        $request = request();
        Session::set('openid', null);
        $map['id'] = $request->param('id');
        $Merchant = new Merchant();
        $Agent = new Agent();
        $WxOpen = new WxOpen();
        $user = $Merchant->where($map)->find();
        $config = $Agent->where(array('id' => $user['agent']))->find();
        $users = $WxOpen->where(array('id' => $config['wx_open_id']))->find();
        $options = array(
            'component_token' => $config['component_token'], // 填写你设定的key
            'component_encodingaeskey' => $config['component_encodingaeskey'], // 填写加密用的EncodingAESKey
            'component_appid' => $config['component_appid'], // 填写高级调用功能的app id
            'component_appsecret' => $config['component_appsecret'], // 填写高级调用功能的密钥
            'open_ticket' => $config['open_ticket'],
            'authorizer_appid' => $users['authorizer_appid'],
            'authorizer_refresh_token' => $users['authorizer_refresh_token'],
            // 'partnerkey'=>$agent['partnerkey']
        );

        $weObj = new Wxobjopen($options);
        $openid = Session::get('openid');
        if (strlen($openid) <= 10) {
            $info = $weObj->getOpenoauthAccessToken();
            if (!$info) {
                $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("huifupay/wxorderinfo", array('id' => $request->param('id'), 'orderid' => $request->param('orderid')));
                $url = $weObj->getopenOauthRedirect($callback, '', 'snsapi_base');

                header("Location: $url");
                exit();
            } else {
                $openid = $info['openid'];
                session('openid', $openid);
            }
        }

        $order = Paylog::where('orderid', $request->param('orderid'))->find();
        if ($openid == $order['openid']) {
            $mav['id'] = $request->param('id');
            $Merchant = new Merchant();
            $shmc = $Merchant->where($mav)->value('merchant');
            $this->assign('shmc', $shmc);
            $this->assign('order', $order);
            $this->assign('id', $request->param('id'));
            $this->assign('orderid', $request->param('orderid'));
        } else {
            $this->error('非订单支付者无法查看订单详情');
        }
        //jssdk
        $url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
        $jssdk = $weObj->getJsSign($url);
        $this->assign('jssdk', $jssdk);
        return $this->fetch('index/orderinfo');
    }

    public function aliorderinfo()
    {
        $request = request();
        $Merchant = new Merchant();
        $Agent = new Agent();
        $users = $Merchant->where(array('id' => $request->param('id')))->find();
        $agent = $Agent->where(array('id' => $users['agent']))->find();
        $raskey = $agent['ali_app_key'];
        $options = array(
            //'token' => $config ["token"], // 填写你设定的key
            //'encodingaeskey' => $config ["encodingaeskey"], // 填写加密用的EncodingAESKey
            'appid' => $agent['ali_app_id'], // 填写高级调用功能的app id
            'rsaPrivateKey' => $agent['ali_app_key'],

        );
        $aliObj = new Alipayobj($options);

        if ($request->param('auth_code') || request()->get('auth_code')) {
            $param['app_id'] = $agent['ali_app_id'];
            $param['method'] = "alipay.system.oauth.token";
            $param['charset'] = "UTF-8";
            $param['sign_type'] = "RSA2";
            $param['version'] = '1.0';
            $param['timestamp'] = date('Y-m-d H:i:s');
            $param['grant_type'] = 'authorization_code';
            $param['code'] = $request->param('auth_code') ? $request->param('auth_code') : $request->get('auth_code');
            $signContent = $aliObj->rsaSign($param, $signType = "RSA2");

            //$sign2 = $aliObj->alonersaSign($signContent, $raskey, $signType = "RSA", $keyfromfile = false);


            $param['sign'] = $signContent;
            $uid = $aliObj->getuid($param);
            $user = json_decode($uid, true);
            $this->uid = $user['alipay_system_oauth_token_response']['user_id'];
//            var_dump($uid);
        } else {

            $callback = 'https://' . $_SERVER ['SERVER_NAME'] . url("huifupay/aliorderinfo", array('id' => $request->param('id'), 'orderid' => $request->param('orderid')));
            $url = $aliObj->getOauthRedirect($callback, '', 'auth_userinfo');
            header("Location: $url");
        }


        $maq['orderid'] = $request->param('orderid');
        $Paylog = new Paylog();
        $order = $Paylog->where($maq)->find();

        $mav['id'] = $request->param('id');
        $Merchant = new Merchant();
        $shmc = $Merchant->where($mav)->value('merchant');


        $this->assign('shmc', $shmc);
        $this->assign('order', $order);
        $this->assign('id', $request->param('id'));
        $this->assign('orderid', $request->param('orderid'));
        return $this->fetch('alipay/orderinfo');
    }

    private function create_paylog($param, $pay_fs)
    {
        $out_trade_no = $param['orderid'];
        if (isset($param['sub_openid'])) {
            $sub_openid = $param['sub_openid'];;
        } elseif (isset($param['buyer_id'])) {
            $sub_openid = $param['buyer_id'];;

        }
        $data['orderid'] = $out_trade_no;
        $data['mid'] = $param['id'];
        $data['openid'] = $sub_openid;
        $data['pay_statu'] = 0;
        $data['pay_fs'] = $pay_fs;
        $data['add_time'] = time();
        $data['attach'] = isset($param['attach']) ? $param['attach'] : "";
        $data['price'] = $param['price'];
        $data['yf_price'] = $param['price'];
        $Paylog = new Paylog();
        $Paylog->save($data);

    }

    public function getorder($sh)
    {
        $order = "H" . $sh . "f" . date('YmdHis') . rand(10000, 99999);
        return $order;

    }

    public function getorder2()
    {
        $request = request();
        if ($request->isAjax()) {
            $sh = $request->post('id');
            $order = "H" . $sh . "f" . date('YmdHis') . rand(10000, 99999);
            echo $order;
        }
    }
}